<?php
/**
 * 「灵感捕手」模块
 */
namespace Beerus\Modules\IdealHome\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\UserNick;
use Doraemon\model\IdealHomeTab\IdealHomeInspirationUser;
use Doraemon\service\IdealHomeTab\v2\Persona;
use Doraemon\service\Member;
use Doraemon\service\Photos;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Box;
use Illuminate\Support\MessageBag;

use Hhzbeads\Img\ImgUrl;

class InspirationUserController extends Controller {
    const PAGE_SIZE = 20;
    const UID_NUM = 5;


    public function __construct()
    {
        parent::__construct();
        Admin::script($this->_addScript());
    }

    public function index(Request $request, Content $content) {
        $page = $request->get('page', 1);
        $pageSize = $request->get('per_page', self::PAGE_SIZE);
        $title = $request->get('title');
        $condition = [];
        if (!empty($title)) {
            $condition['title[~]'] = $title;
        }
        $status = $request->get('status');
        if(!empty($status)) {
            $condition['data_status'] = $status;
        }

        $total = IdealHomeInspirationUser::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = IdealHomeInspirationUser::selectByWhere($condition, '*');
        foreach($list as $k => $v) {
            $list[$k]['data'] = json_decode($v['data'], true);

        }
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        //获取域名前缀
        $preUrl = str_replace('beerus.', 'frieza.', str_replace('admin/IdealHome/InspirationUser/index', '', $request->url()));

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $preUrl) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
//                $grid->disableCreateButton();
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(5, function ($filter) {
                        $filter->equal('title', '人设')->placeholder('请输入人设');
                    });
                    $filter->column(5, function ($filter) {
                        // 状态
                        $filter->equal('status', '状态')->select(IdealHomeInspirationUser::STATUS_LIST);
                    });
                    $filter->expand();
                });

                $grid->column('created_at', '创建时间')->width(120)->display(function () {
                    return mb_substr($this->created_at, 0, 16);
                });;
                $grid->column('title', '人设')->width(150);
                $grid->column('nicknames', '账号昵称')->width(200)->display(function (){
                    $str = '';
                    foreach ($this->data as $d) {
                        $str .=  UserNick::uid2nick($d['uid'])."<br />";
                    }
                    return $str;
                });
                $grid->column('uids', 'UID')->width(100)->display(function () use ($preUrl) {
                    $str = '';
                    foreach ($this->data as $d) {
                        $str .=  "<a href='".$preUrl."admin/user/Detail/".$d['uid']."' target='_blank'>".$d['uid']."</a><br />";
                    }
                    return $str;
                });
                $grid->column('noteIds', 'note id')->width(160)->display(function () use ($preUrl) {
                    $str = '';
                    foreach ($this->data as $d) {
                        $str .=  "<a href='".$preUrl."admin/photo/photoList/index?note_id=".$d['noteId']."' target='_blank'>".$d['noteId']."</a><br />";
                    }
                    return $str;
                });
                $grid->column('pics', '配图')->width(200)->display(function (){
                    $str = '';
                    foreach ($this->data as $d) {
                        $str .= '<a  href="javascript:layer.open({
                                type: 2,
                                title: \'【'.$d['noteId'].'】配图\',
                                maxmin: false,
                                area: [\'600px\', \'600px\'],
                                content: \'/admin/IdealHome/InspirationUser/notePic/' . $d['noteId'].'/' . $d['picId'].'\'
                            });">点击查看图片</a><br />';
                    }
                    return $str;
                });
                $grid->column('status', '状态')->width(80)->display(function () {
                    return IdealHomeInspirationUser::STATUS_LIST[$this->data_status];
                });;
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->disableView();
                    if ($actions->row->data_status == IdealHomeInspirationUser::STATUS_WAIT) {
                        $actions->append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onclick=\"return confirm('确认上线该人设吗？')\" href=\"status/" .
                            $actions->row->id . "/".$actions->row->data_status."\" class=\"btn btn-sm btn-default\">上线</a>");
                        $actions->append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a  href=\"" .
                            $actions->row->id . "/edit\" class=\"btn btn-sm btn-default\">编辑</a>");
                    } else if ($actions->row->data_status == IdealHomeInspirationUser::STATUS_ONLINE){
                        $actions->append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onclick=\"return confirm('「已下线」的人设记录无法再次上线, 确认下线该人设吗？')\" href=\"status/" .
                            $actions->row->id . "/".$actions->row->data_status."\" class=\"btn btn-sm btn-default\">下线</a>");
                    }
                });
            }
        );
        return $content
            ->header('「灵感捕手」模块列表')
            ->row($gridList);
    }

    /**
     * 获取note图片
     * @param Request $request
     * @param Content $content
     * @param string $noteId
     * @param string $picId
     * @return string
     */
    public function notePic(Request $request, Content $content, $noteId = '', $picId = '') {
        if (!empty($picId)) {
            return '<img style="width:100%;height:auto" src="'. ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $picId, ImgUrl::IMAGE_SIZE_ORI_NPHONE).'">';
        }
        $noteInfo = Photos::getPhoto($noteId);
        if (empty($noteInfo) || empty($noteInfo['pic_org_id'])) {
            return '<label>未找到配图～</label>';
        }
        return '<img style="width:100%;height:auto;=='.$noteInfo['pic_org_id'].'==" src="'. ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $noteInfo['pic_org_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE).'">';

    }

    /**
     * 更改人设状态
     * @param Request $request
     * @param Content $content
     * @param int $id
     * @param int $status
     * @return \Illuminate\Http\RedirectResponse
     */
    public function status(Request $request, Content $content, $id = 0, $status = 2) {
        $upStatus = IdealHomeInspirationUser::STATUS_WAIT;
        if (IdealHomeInspirationUser::STATUS_ONLINE == $status ) { //展示中变为已下线
            $upStatus = IdealHomeInspirationUser::STATUS_OFFLINE;
        } else if (IdealHomeInspirationUser::STATUS_WAIT == $status ) { //待上线的变为展示中
            $upStatus = IdealHomeInspirationUser::STATUS_ONLINE;
        } else {
            $error = new MessageBag([
                'title' => '状态不对应'
            ]);
            return back()->with(compact('error'));
        }

        $result = IdealHomeInspirationUser::updateData([
            'data_status' => $upStatus
        ], [
            'id' => $id,
            'data_status' => $status
        ]);

        if (empty($result)) {
            $error = new MessageBag([
                'title' => '状态变更失败'
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '状态更改成功'
        ]);
        if (IdealHomeInspirationUser::STATUS_ONLINE == $upStatus) {
            // 获取noteId、标题及note图片
            $item = IdealHomeInspirationUser::getPersonaItem($id);
            if (empty($item)) {
                $error = new MessageBag([
                    'title' => '通知失败'
                ]);
                return back()->with(compact('error'));
            }
            $data = json_decode($item['data'], true);
            $uids = array_column($data, 'uid');
            //发送下行
            Persona::sendNotice2OnlinePersonaUsers($id, $uids);

        }

        return back()->with(compact('success'));
    }

    public function _columnForm(Request $request, Content $content, $id = 0, $isView = false) {

        $info = [];
        if ($id) {
            $info = IdealHomeInspirationUser::getByWhere(['id' => $id]);
            $info['data'] = json_decode($info['data'], true);
        }
        if (empty($info['data'])) {
            $info['data'] = $this->_createData();
        }


        $form = new Form($info);
        $form->attribute(['id' => 'widget-form-inspiration']);



//        $form->disableReset();
//        $form->disableSubmit();
        if ($isView) {
            $form->disableSubmit();
        }
        if ($id) {
            $form->hidden('id');
        }
        $form->text('title', '人设')->required()->placeholder('最多7个字')
            ->setWidth(4, 1)->attribute('maxlength',7);


//        $form->table('data', function ($table) {
//            $table->text('uid', 'uid')->required();
//            $table->text('desc', '简介--');
//            $table->text('note_id', 'note_id');
//            $table->imgUpload('pic_id', 'banner图', false)->setMinImageHeight(100)->setMaxImageHeight(100)->setMinImageWight(100)->setMaxImageWight(100)
//            ->setWidth(100);
//        })->setWidth(12)->disableCreate()->disableDelete();


        foreach ($info['data'] as $rk => $row) {

            $form->html('<hr class="clearfix col-md-12 col-sm-12" />')->setWidth(12, 0);
            //imgUpload 会覆盖之前的图片， 统一‍使用下标
            $form->text('data.'.$rk.'.uid', '用户UID'.($rk+1))->required()->setWidth(9, 3)
                ->setGroupClass('pull-left col-md-4 col-sm-4 tip-input uid-input-'.$rk);
            $form->text('data.'.$rk.'.desc', '简介')->required()->setWidth(9, 3)
                ->placeholder('最多14个字')->attribute('maxlength',14)
                ->setGroupClass('pull-left col-md-4 col-sm-4');
            $form->text('data.'.$rk.'.noteId', 'note id')->required()->setWidth(9, 3)
                ->setGroupClass('pull-left col-md-4 col-sm-4 tip-input note-input-'.$rk);
            $form->imgUpload('data.'.$rk.'.picId', '配图', false, ['imgType' => ImgUrl::APPTYPE_APP, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE])
                ->setWidth(5, 1)->setGroupClass('clearfix col-md-12 col-sm-12');

        }


        $form->action(url('admin/IdealHome/InspirationUser/save'));
//        $form->confirm('确认提交吗？');
        $title = '新增';
        if ($id) {
            $title = $isView ? '查看' : '编辑';
            $title = $title.'【'.$info['title'].'】「'.IdealHomeInspirationUser::STATUS_LIST[$info['data_status']].'」';
        }
        $box = new Box($title, $form);

        return $content
            ->header('灵感捕手模块配置')
            ->description($title)
            ->breadcrumb(
                ['text' => '灵感捕手列表', 'url' => url('admin/IdealHome/InspirationUser/index')],
                ['text' => $title]
            )
            ->row($box);
    }

    /**
     * 创建人设
     * @param Request $request
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function create(Request $request, Content $content, $id = 0) {
        return $this->_columnForm($request, $content);
    }

    /**
     * 编辑人设
     * @param Request $request
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function edit(Request $request, Content $content, $id = 0) {
        return $this->_columnForm($request, $content, $id);
    }


    /**
     * 查看人设
     * @param Request $request
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function view(Request $request, Content $content, $id = 0) {
        return $this->_columnForm($request, $content, $id, true);
    }


    /**
     * 初始化人设数据
     * @return array
     */
    protected function _createData() {
        $data = [];
        for ($i = 0; $i < self::UID_NUM; $i ++) {
            $data[] = ['uid' => '', 'desc' => '', 'noteId' => '', 'picId' => ''];
        }
        return $data;
    }

    /**
     * 保存人设
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function save(Request $request)
    {
        $params = $request->all();

        $id = $params['id'];
        if (!empty($id)) {
            $info = IdealHomeInspirationUser::getByWhere(['id' => $id]);
            if (empty($info)) {
                $id = 0;
            } else if (IdealHomeInspirationUser::STATUS_WAIT != $info['data_status']) {
                return self::responseData([], '只有「待上线」的才能编辑');
            }

        }

        $title = $params['title'];

        $uidArr = [];
        $noteIdArr = [];

        $data = [];
        foreach ($params['data'] as $i =>  $d) {

            $desc = $d['desc'];
            $picId = $d['picId'];
            $noteId = $d['noteId'];
            $uid = $d['uid'];
            if (in_array($uid, $uidArr)) {
                return self::responseData([
                    'index' => $i,
                    'msg' => 'uid【'.$uid.'】重复'
                ], 'uid【'.$uid.'】重复', 2);
            }

            if (in_array($noteId, $noteIdArr)) {
                return self::responseData([
                    'index' => $i,
                    'msg' => 'note id【'.$noteId.'】重复'
                ], 'note id【'.$noteId.'】重复', 3);

            }

            $uidArr[] = $uid;
            $noteIdArr[] = $noteId;


            $data[] = [
                'desc' => $desc,
                'picId' => $picId,
                'noteId' => $noteId,
                'uid' => $uid
            ];
        }
        //获取用户信息
        $userInfoList = Member::getUserInfoByUserIds($uidArr);
        if (count($userInfoList) != self::UID_NUM) {
            for ($i = 0; $i < self::UID_NUM; $i ++) {
                $uid = $uidArr[$i];
                if (empty($userInfoList[$uid])) {
                    //对比uid， 提示
                    return self::responseData([
                        'index' => $i,
                        'msg' => 'uid【'.$uid.'】不存在'
                    ], 'uid【'.$uid.'】不存在', 2);
                }
            }

        }

        //获取note信息
        $photoList =  Photos::getPhotos($noteIdArr);
        for ($i = 0; $i < self::UID_NUM; $i ++) {
            $noteId = $noteIdArr[$i];
            if (empty($photoList[$noteId])) {
                //对比note ， 提示
                return self::responseData([
                    'index' => $i,
                    'msg' => 'noteId【'.$noteId.'】不存在'
                ], 'noteId【'.$noteId.'】不存在', 3);
            } else if($photoList[$noteId]['uid'] != $uidArr[$i]) {
                //对比uid， 提示
                return self::responseData([
                    'index' => $i,
                    'msg' => '未找到匹配UID的note【'.$noteId.'】，请检查是否填写正确'
                ], '未找到匹配UID的note【'.$noteId.'】，请检查是否填写正确', 3);

            }
        }
        if (!empty($id)) {
            $res = IdealHomeInspirationUser::updateData(
                ['title' => $title, 'data' => json_encode($data, JSON_UNESCAPED_UNICODE)],
            ['id' => $id]);

        } else {
            $res = IdealHomeInspirationUser::insertData(['title' => $title, 'data' => json_encode($data, JSON_UNESCAPED_UNICODE)]);

        }
        if(empty($res)) {
            return self::responseData([], '保存失败');
        } else {
            return self::responseData([], '保存成功', 1);
        }


    }

    /**
     * 格式化提交返回数据
     * @param array $data
     * @param string $msg
     * @param int $code
     * @return \Illuminate\Http\JsonResponse
     */
    public function responseData($data = [] , $msg = '保存失败', $code = 0) {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
        exit();
    }

    protected  function _addScript() {
        return <<<SCRIPT
        $("#widget-form-inspiration").submit(function () {
            console.log($(this).parseForm());
            $.post("/admin/IdealHome/InspirationUser/save", $(this).parseForm(), function(data){
                console.log(data);
                
                if(data.code == 1) {
                    layer.msg(data.msg);
                    window.location.replace('/admin/IdealHome/InspirationUser/index');
                } else if (data.code == 2 || data.code == 3) {
                    $("#widget-form-inspiration").find('.help-block').each(function(index){
	                    $(this).remove();
                    });
                    $("#widget-form-inspiration").find('.has-error').each(function(index){
	                    $(this).removeClass('has-error');
                    });
                    let o = 'uid';
                    if(data.code == 3) {
                        o = 'note';
                     }
                    $('.'+o+'-input-'+data.data.index).addClass('has-error');
                    $('.'+o+'-input-'+data.data.index).find('input').focus();
                    $('.'+o+'-input-'+data.data.index).find('.col-sm-9').append('<span class="help-block">'+data.data.msg+'</span>');
                } else {
                    layer.msg(data.msg);
                }
            });
            return false;
        });
        $('body').on('change', '#widget-form-inspiration input', function(e){
            let p = $(this).parent().parent().parent();
            if(p.hasClass('has-error')) {
                p.removeClass('has-error');
                p.find('.help-block').remove();
            }
        });
        $('body').on('click', '#widget-form-inspiration .kv-file-remove', function(e){
            $(this).parent().parent().parent().parent().parent().parent().parent().parent().find('input').val('');
        });
        $(function(){
            $("#widget-form-inspiration").find(".box-footer").find(".pull-left").html("<a href=\"javascript:history.back(-1)\" class=\"btn btn-default pull-right\">取消</a>");
        });
        $.fn.parseForm=function(){
            var o = {};
            var a = this.serializeArray();
            $(a).each(function(){
                if (this.name.indexOf("user_profile") == -1) {
                    if(o[this.name]){
                        if($.isArray(o[this.name])){
                            o[this.name].push(this.value);
                        }else{
                            o[this.name]=[o[this.name],this.value];
                        }
                    }else{
                        o[this.name]=this.value; 
                    }
                }
            });
            return o;
        };
SCRIPT;

    }




}
